// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const { userId } = event;
  const { OPENID } = cloud.getWXContext();

  try {
    // 查询用户信息
    const userResult = await db.collection("users").doc(userId).get();
    const user = userResult.data;

    // 如果是商家，获取商家信息
    if (user.userType === "merchant") {
      const merchantResult = await db
        .collection("merchants")
        .where({
          _openid: OPENID,
        })
        .get();
      if (merchantResult.data.length > 0) {
        user.merchantInfo = merchantResult.data[0];
      }
    }

    return {
      code: 0,
      msg: "获取成功",
      data: user,
    };
  } catch (err) {
    console.error(err);
    return {
      code: -1,
      msg: "获取失败",
      error: err,
    };
  }
};
